#include "info.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

/*
struct rentry analyze(char* buffer){
    char method[50];
    char path[200];
    char version[50];

    int i,j;


    memset(method,'\0',sizeof(method));
    memset(path,'\0',sizeof(path));
    memset(version,'\0',sizeof(version));

    char* p=buffer;
    char* header=NULL;
    struct rentry r;

    //Copy method
    for(i=0;*p!='\r';i++){
        if(*(p+i)==' ')
        {
            strncpy(method,p,i);
            p=p+i+1;
            break;
        }
    }

    //Copy path
    for(i=0;*p!='\r';i++){
        if(*(p+i)==' ')
        {
            strncpy(path,p,i);
            p=p+i+1;
            break;
        }
    }

    //Copy verion
    for(i=0;;i++){
        if(*(p+i)=='\r')
        {
            strncpy(version,p,i);
            p+=i;
            break;
        }
    }

    if (strcmp(method,"GET"))
    {
        header="HTTP/1.0 400 Bad Request: Invalid Method: ";
        strcat(header,method);


    }
    else if (strcmp(version,"HTTP/1.0") && strcmp(version,"HTTP/1.1"))
    {
        header="HTTP/1.0 400 Bad Request: Invalid HTTP-Version: ";
        strcat(header,version);
    }
    else if (strpbrk(path," <>#%"))
    {
        header="HTTP/1.0 400 Bad Request: Invalid URI: ";
        strcat(header,path);
    }



    //printf("method:%s,path:%s,version:%s",method,path,version);

    return r;
}

*/


char* response(struct rentry r, long int *size){
    FILE *fl;
    fl=fopen("abc.jpg","rb");
    fseek(fl,0,SEEK_END);
    long len=ftell(fl);
    char *content=(char*)malloc(len);
    fseek(fl,0,SEEK_SET);
    fread(content,1,len,fl);
    int ret=fclose(fl);

    char* header="HTTP/1.0 200 OK\r\nContent-Type:image/png\r\nContent-Length:\0";
    char length[20];
    char* space="\r\n\r\n\0";
    int len_num=itoa(len,length);
    char* resp=(char*)malloc(sizeof(header)+sizeof(length)+len+4);
    memset(resp,'\0',sizeof(resp));
    strcat(resp,header);
    strcat(resp,length);
    strcat(resp,space);
    strcat(resp,content);

    //!!!!DON'T forget to release the memoery


    //Test file write
/*
    fl=fopen("test.png","wb");
    ret=fwrite(content,len,1,fl);
    fclose(fl);
*/


    *size=sizeof(header)+sizeof(length)+sizeof(space)+len;
    return resp;
    
    

}
  /* reverse:  reverse string s in place */
 void reverse(char s[])
 {
     int i, j;
     char c;

     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
 }

 int itoa(long n, char s[])
 {
     int i, sign;

     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */

     s[i] = '\0';
     reverse(s);
     return i;
 }

